//Copyright 2008 Kristian Gundry And Rune Juhl-Petersen
//This file is part of Plain.

//Plain is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//any later version.

//Plain is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Lesser General Public License for more details.

//You should have received a copy of the GNU Lesser General Public License
//along with Plain.  If not, see <http://www.gnu.org/licenses/>.
using Plain.Utilities.Query;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Plain.Utilities{
	/// <summary>
	/// Description of QueryExtensions.
	/// </summary>
	public static class QueryExtensions{
		public static IQueryResult<T> find<T>(this object o){
			return null;
		}
		public static IQueryResult<T> findAll<T>(this object o){
			Dictionary<object,object> beenThere = new Dictionary<object,object>();
			IList<T> list = new List<T>();
			HandleObject(o,list,beenThere);
			return new QueryResult<T>(list);
		}
		private static void HandleObject<T>(object o,IList<T> list, IDictionary<object,object> beenThere){
            if (o.GetType().IsValueType ) {
                if (o is T) {
                    list.Add((T)o);
                }
            } else if(!beenThere.ContainsKey(o)){
                
				beenThere.Add(o,null);
				if(o is T){
					list.Add((T)o);
				}
				if(o is IEnumerable){
					foreach(object listItem in (IEnumerable)o){
						HandleObject(listItem,list,beenThere);
					}
				}
				foreach(PropertyInfo prop in o.GetType().GetProperties()){
                    if (prop.Name != "Page" && prop.Name != "Parent") {
                        try {
                            HandleObject(prop.GetValue(o, null), list, beenThere);
                        } catch { }
                    }
				}
			}
		}
		
	}
}
